package Task3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientSocket {
    public static void main(String[] args) {
        //1. 创建Socket类型的队形并提供服务器的主机名和端口号
        Socket s = null;
        PrintStream ps = null;
        Scanner sc = null;
        BufferedReader bf = null;
        try {
            s = new Socket("192.168.1.59", 8888);
            System.out.println("连接服务器成功！");
            // 1.使用输入输出流通讯
            sc = new Scanner(System.in);
            ps = new PrintStream(s.getOutputStream());
            bf = new BufferedReader(new InputStreamReader(s.getInputStream()));

            while(true) {
                //2. 输入输出流进行通信 ---> 客户端向服务器发送字符串
                System.out.println("请客户输入需要发送的消息...");
                String input = sc.next();
                ps.println(input);
                System.out.println("客户端发送数据成功！");

                //3.实现客户端接收服务器发来的消息
                String str = bf.readLine();
                System.out.println("服务器回发的消息:" + str);

                //4. 控制聊天结束
                if(input.equals("结束通讯")){
                    System.out.println("通讯结束！");
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bf != null) {
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (ps != null) {
                ps.close();
            }

            if (sc != null) {
                sc.close();
            }
        }
    }
}
